package com.example.singletest.order;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class OrderProducer {
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    /**
     * 直接发送消息
     * */
    public void sendOrderCreatedEvent(String orderId) {
        rocketMQTemplate.convertAndSend("ORDER_TOPIC", orderId);
    }

    /**
     * 把“发出去”变成“一定发成功”
     * */
    public void sendOrderCreatedEventReliability(String orderId) {
        SendResult sendResult = rocketMQTemplate.syncSend(
                "ORDER_TOPIC",
                MessageBuilder.withPayload(orderId).build(),
                3000,           // 超时 3 秒
                3                       // 重试 3 次
        );
        if (sendResult.getSendStatus() != SendStatus.SEND_OK) {
            // 记录日志并报警
            log.error("消息发送失败 orderId={}", orderId);
            //System.out.println("消息发送失败 orderId= '"+orderId+"' ");
        }
    }

    public void sendTxOrderCreatedEvent(String orderId) {
        Message<String> msg = MessageBuilder.withPayload(orderId).build();
        rocketMQTemplate.sendMessageInTransaction(
                "ORDER_TOPIC",   // 必须和 yml 中的 producer.group 同名
                msg,
                orderId              // 透传到 executeLocalTransaction
        );
    }
}
